import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

public class WordCount {
    public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException {
        Configuration conf=new Configuration();
        System.setProperty("HADOOP_USER_NAME","root");
        conf.set("mapreduce.app-submission.cross-platform","true");
        Job job=Job.getInstance(conf,"wc");
        job.setJarByClass(WordCount.class);
        job.setJar(System.getProperty("user.dir")+"\\target\\mr-1.0.jar");
        job.setMapperClass(WordCountMapper.class);
        job.setReducerClass(WordCountReducer.class);
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(IntWritable.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(IntWritable.class);
        FileInputFormat.setInputPaths(job,new Path("hdfs://node01:9000/wc/in"));
        FileOutputFormat.setOutputPath(job,new Path("hdfs://node01:9000/wc/out"));
        System.out.println(job.waitForCompletion(true)?0:1);
    }
    class WordCountMapper extends Mapper<LongWritable, Text,Text, IntWritable> {
        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            String[] words=value.toString().split(" \t");
            for (String word:words) {
                context.write(new Text(word),new IntWritable(1));
            }
        }
    }
     class WordCountReducer extends Reducer<Text, IntWritable,Text, IntWritable> {
        @Override
         protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
             int count=0;
             for (IntWritable value:values) {
                 count+=value.get();
             }
             context.write(key,new IntWritable(count));
         }
    }
}
